<?php

namespace app\mobile\controller;

use app\admin\service\NodeService;
use app\mobile\service\CompanyService;
use app\admin\service\PointService;
use app\admin\service\CompanyService as AdminComService;
use app\admin\service\ArchivesService;
use app\mobile\validate\Company as CompanyValidate;
use app\admin\service\MemberService;
use app\common\service\WxTokenService;
use library\Controller;
use think\Db;

/**
 * 登录
 * Class Login
 * @package app\mobile\controller
 */
class Login extends Controller
{
    /**
     * 登录
     */
    public function index()
    {
        if ($this->request->isGet()) {      	
            $isLogin = CompanyService::IsLogin();
            if ($isLogin) {
                $this->redirect('mobile/index/index');
            } else {
                $this->loginskey = session('loginskey');
                if (empty($this->loginskey)) {
                    $this->loginskey = uniqid();
                    session('loginskey', $this->loginskey);
                }
                $this->fetch();
            }
        } else {
        	$params = $this->request->post();
        	if(empty($params['verify'])){
        		//用户名密码登录  
        		$data = $this->_input([
	                'username' => trim($this->request->post('username')),
	                'password' => trim($this->request->post('password')),
	                'platform' => trim($this->request->post('platform')),
	            ], [
	                'username' => 'require|min:6',
	                'password' => 'require|min:6',
	                'platform' => 'require|in:1,2',
	            ], [
	                'username.require' => '登录账号不能为空！',
	                'password.require' => '登录密码不能为空！',
	                'platform.require' => '登录平台不能为空！',
	                'username.min' => '登录账号长度不能少于6位有效字符！',
	                'password.min' => '登录密码长度不能少于6位有效字符！',
	                'platform.in' => '登录平台数值错误',
	            ]);
	            $map = ['loginname' => $data['username'], 'type' => 1];
	            $user = Db::name('SystemMember')->where($map)->find();
	            if (empty($user)) $this->error('未查询到相关信息，请重新输入!');
	            if ($user['status'] != 1) $this->error('账号已经被禁用，请联系客服!');
	            // 账号锁定消息
	            $cache = cache("user_login_{$user['loginname']}");
	            if (is_array($cache) && !empty($cache['number']) && !empty($cache['time'])) {
	                if ($cache['number'] >= 10 && ($diff = $cache['time'] + 3600 - time()) > 0) {
	                    list($m, $s, $info) = [floor($diff / 60), floor($diff % 60), ''];
	                    if ($m > 0) $info = "{$m} 分";
	                    $this->error("<strong class='color-red'>抱歉，该账号已经被锁定！</strong><p class='nowrap'>连续 10 次登录错误，请 {$info} {$s} 秒后再登录！</p>");
	                }
	            }
	            if (md5($user['password'] . session('loginskey')) !== $data['password']) {
	                if (empty($cache) || empty($cache['time']) || empty($cache['number']) || $cache['time'] + 3600 < time()) {
	                    $cache = ['time' => time(), 'number' => 1, 'geoip' => $this->request->ip()];
	                } elseif ($cache['number'] + 1 <= 10) {
	                    $cache = ['time' => time(), 'number' => $cache['number'] + 1, 'geoip' => $this->request->ip()];
	                }
	                cache("user_login_{$user['loginname']}", $cache);
	                if (($diff = 10 - $cache['number']) > 0) {
	                    $this->error("<strong class='color-red'>登录账号或密码错误！</strong><p class='nowrap'>还有 {$diff} 次尝试机会，将锁定一小时内禁止登录！</p>");
	                } else {
	                    sysoplog('系统管理', "账号{$user['loginname']}连续10次登录密码错误，请注意账号安全！");
	                    $this->error("<strong class='color-red'>登录账号或密码错误！</strong><p class='nowrap'>尝试次数达到上限，锁定一小时内禁止登录！</p>");
	                }
	            }
	            // 登录成功并更新账号
	            cache("user_login_{$user['loginname']}", null);
	            Db::name('SystemMember')->where(['id' => $user['id']])->update([
	                'login_at' => time(), 'login_ip' => $this->request->ip(), 'login_source' => 2,'login_num' => Db::raw('login_num+1'),
	            ]);
				session('loginskey', null);
	            session('company_user', $user);
	            sysoplog('用户登陆', '用户登录系统成功');           
	            $scheme = $_SERVER['REQUEST_SCHEME'] == 'http' ? 'http://' : 'https://';
	            $index_url = $scheme . $_SERVER['SERVER_NAME'] . '/mobile/index/index';			
	            if($data['platform'] == 1){
	            	//微信内需要获取openid，先组装url获取code				
					$wxtoken = new WxTokenService();
					$baseUrl = urlencode($index_url);
					$url = $wxtoken->__CreateOauthUrlForCode($baseUrl,'STATE');
		            $this->success('微信内部环境', ['url'=>$url]);
	            }else{           	
	            	$this->success('微信外部环境', ['url'=>$index_url]);
	            } 
        	}else{
        		//手机号验证码登录  
        		$data = $this->_input([
	                'mobile' => trim($this->request->post('mobile')),
	                'verify' => trim($this->request->post('verify')),
	                'platform' => trim($this->request->post('platform')),
	            ], [
	                'mobile' => 'require|mobile',
	                'verify' => 'require|number|length:4',
	                'platform' => 'require|in:1,2',
	            ], [
	                'mobile.require' => '手机号必须填写',
	                'mobile.mobile' => '手机号格式错误',
	                'verify.require' => '验证码必须填写',
	                'verify.number' => '验证码格式错误',
	                'verify.length' => '验证码为4位',
	                'platform.in' => '登录平台数值错误',
	            ]);
	            $map = ['mobile' => $data['mobile'], 'type' => 1];
	            $user = Db::name('SystemMember')->where($map)->find();
	            if (empty($user)) $this->error('未查询到相关信息，请重新输入!');
	            if ($user['status'] != 1) $this->error('账号已经被禁用，请联系客服!');
	            $verify = Db::name('system_verify')
						->where(['mobile'=>$data['mobile'],'status'=>0,'type'=>2])
						->order('create_at desc')
						->find();
				if(!$verify || $data['verify'] != $verify['code']){
					$this->error('验证码错误');
				}		
				if(time() - $verify['create_at'] > 900){
					$this->error('验证码已失效');
				}
	            // 登录成功并更新账号
	            cache("user_login_{$user['loginname']}", null);
	            Db::name('SystemMember')->where(['id' => $user['id']])->update([
	                'login_at' => time(), 'login_ip' => $this->request->ip(), 'login_source' => 2,'login_num' => Db::raw('login_num+1'),
	            ]);
				session('loginskey', null);
	            session('company_user', $user);
	            sysoplog('用户登陆', '用户登录系统成功');           
	            $scheme = $_SERVER['REQUEST_SCHEME'] == 'http' ? 'http://' : 'https://';
	            $index_url = $scheme . $_SERVER['SERVER_NAME'] . '/mobile/index/index';			
	            if($data['platform'] == 1){
	            	//微信内需要获取openid，先组装url获取code				
					$wxtoken = new WxTokenService();
					$baseUrl = urlencode($index_url);
					$url = $wxtoken->__CreateOauthUrlForCode($baseUrl,'STATE');
		            $this->success('微信内部环境', ['url'=>$url]);
	            }else{           	
	            	$this->success('微信外部环境', ['url'=>$index_url]);
	            } 
        	}                       
        }

    }
    
    
    /**
     * 注册
     */
    public function register()
    {
    	if($this->request->isPost()){
    		$data = $this->request->post();
    		if(empty($data) || !$data){
    			$this->error('数据错误');
    		}
    		trim_array($data);    		
    		$validate = new CompanyValidate;
    		if (!$validate->scene('reg')->check($data)) {
	            $this->error($validate->getError());
	        }
	        //检查手机号是否被注册
	        $find = Db::name('system_member')->where(['mobile'=>$data['mobile'],'type'=>1])->find();
	        if($find){
	        	$this->error('手机号码已注册，请更改手机号码');
	        }
	        $mid = MemberService::member_add($data['name'],$data['password'],1,2,1,0);
	        if(!$mid){
            	$this->error('注册失败，请稍后再试');
            }
	        if($mid == -1){
            	$this->error('公司已存在，请更改公司名称');
            } 
            //更新手机号
            Db::name('system_member')->where(['id'=>$mid])->update(['mobile'=>$data['mobile']]);        
            $arr = [
            	'mid' => $mid,
            	'uid' => 10000,
            	'unique' => number_rule_max(2),
            	'name' => $data['name'],
            	'source' => 2
            ];
            $re = Db::name('system_company')->insert($arr);
            if(!$re){
            	$this->error('注册失败，请稍后再试');
            }
            save_number_rule_max(2);
            // 登录成功并更新账号
            Db::name('SystemMember')->where(['id' => $mid])->update([
                'login_at' => time(), 'login_ip' => $this->request->ip(), 'login_num' => Db::raw('login_num+1'),
            ]);
            Db::name('system_verify')->where(['mobile'=>$data['mobile'],'code'=>$data['verify'],'type'=>1])->update(['status'=>1]);
            $user = Db::name('SystemMember')->where(['id' => $mid])->find();
            session('company_user', $user);
            sysoplog('用户登陆', '用户登录系统成功');
            $scheme = $_SERVER['REQUEST_SCHEME'] == 'http' ? 'http://' : 'https://';
            $index_url = $scheme . $_SERVER['SERVER_NAME'] . '/mobile/index/index';	
            if($data['platform'] == 1){
            	//微信内需要获取openid，先组装url获取code				
				$wxtoken = new WxTokenService();
				$baseUrl = urlencode($index_url);
				$url = $wxtoken->__CreateOauthUrlForCode($baseUrl,'STATE');
	            $this->success('微信内部环境', ['url'=>$url]);
            }else{
            	$this->success('微信外部环境', ['url'=>$index_url]);
            }            
    	}else{
    		// 登录状态检查
    		$isLogin = CompanyService::IsLogin();
    		if($isLogin){
    			$this->redirect('mobile/index/index');
    		}else{             
                $this->fetch();
            }
    	}
    }
    
    
    /**
     * 忘记密码
     */
    public function forgetpw(){
    	if($this->request->isGet()){
    		// 登录状态检查
    		$isLogin = CompanyService::IsLogin();
    		if ($isLogin){
    			$this->redirect('mobile/index/index');
    		}else{
    			$this->fetch();
    		} 		
    	}else{
    		$data = $this->request->post();
    		trim_array($data);
    		$find = Db::name('system_member')->where(['loginname'=>$data['name'],'type'=>1])->find();
    		if(!$find){
    			$this->error('公司名称错误！');
    		}
    		if($find['status'] == 0){
    			$this->error('公司已被冻结！');
    		}
    		if(!$find['mobile']){
    			$this->error('请先绑定手机号！');
    		}
    		$this->success('查询成功！', ['mobile'=>$find['mobile']]);  		
    	} 	
    }
    
    
    /**
     * 忘记密码 -- 验证短信验证码是否正确
     */
    public function forgetpw_check(){
    	$data = $this->request->post();
    	trim_array($data);
    	$verify = Db::name('system_verify')->where(['mobile'=>$data['mobile'],'type'=>3,'status'=>0])->order('id desc')->limit(1)->find();
        if(!$verify || $verify['code'] != $data['verify']){
        	$this->error('验证码错误');       	
        }
        if(time() - $verify['create_at'] > 900){
        	$this->error('验证码已失效');       	
        }
        Db::name('system_verify')->where(['id'=>$verify['id']])->update(['status'=>1]);
        $this->success('验证成功！');
    }
    
    
    /**
     * 忘记密码 -- 修改密码
     */
    public function forgetpw_modify(){
    	$data = $this->request->post();
    	trim_array($data);
        $validate = new CompanyValidate;
		if (!$validate->scene('forgetpw_modify')->check($data)) {
            $this->error($validate->getError());
        }
        //检查手机号是否被注册
        $find = Db::name('system_member')->where(['mobile'=>$data['mobile'],'type'=>1])->find();
        if(!$find){
        	$this->error('该手机号未注册');
        }
        if($find['status'] == 0){
        	$this->error('该手机号已冻结');
        }
        $password = md5($data['password']);
    	Db::name('system_member')->where(['mobile'=>$data['mobile'],'type'=>1])->update(['password'=>$password]);
    	$this->success('修改成功！', url('mobile/login/index'));
    }
    
    
    /**
     * 政策协议
     */
    public function agreement()
    {
    	$agreement =  Db::name('system_agreement')->where(['id' => 1,'is_deleted'=>0])->find();
    	$this->agreement = $agreement;
    	$this->fetch();
    }
    
	
	/**
     * 平台跳转
     */
    public function platform()
    {
    	$this->fetch();
    }
	

    /**
     * 退出
     */
    public function logout()
    {
        \think\facade\Session::clear();
        \think\facade\Session::destroy();
        $this->redirect('@mobile/login');
    }
    
    
    
    
	
	
	//扣除账户管理服务点数或次数
	public function reshContra()
    {
    	$fixed_date = date('Y-m-26', time());
		$date = date("Y-m-d",time());
		if($date == $fixed_date){
			//扣除账户管理费用
			//获取账户管理服务id
			$service = Db::name('system_service')->where(['is_special'=>1])->find();
			$list = Db::name('system_contract')->where('status',1)->select();
			if($list){
				foreach($list as $k=>$v){
					$master = AdminComService::getMaster($v['company_id']);
					$deduction = PointService::deduction_check($v['company_id']);
					$desc = $v['code'].'-'.$service['title'];
					if($deduction == 1){
						//扣除服务点
						$re = PointService::pointDetAdd($master['mid'],$v['mid'],$v['id'],2,$service['point'],$desc,$master['unique']);
						if($re){
							Db::name('system_company')->where(['mid'=>$master['mid']])->setDec('point', $service['point']);
						}
					}else{
						//扣除次数
						$re = PointService::frequencyDetAdd($master['mid'],$v['mid'],$v['id'],$service['id'],2,1,$desc,$master['unique']);
						if($re){
							Db::name('system_member_count')->where(['member_id'=>$master['mid'],'service_id'=>$service['id']])->setDec('surplus');
							Db::name('system_member_count')->where(['member_id'=>$master['mid'],'service_id'=>$service['id']])->setInc('used');
						}
					}
				}
			}
			
		}

    }


	//扣除档案服务点数或次数
	public function reshArchives()
	{
		//获取账户管理服务id
		$service = Db::name('system_service')->where(['is_special'=>3])->find();
		$list = Db::name('system_contract')->where(['status'=>2,'person_status'=>1])->select();
		$now = date("m-d",time());
		if($list){
			foreach($list as $k=>$v){				
				$nextdate = date("m-d",strtotime($v['into_date']));
				if($now == $nextdate){
					$master = AdminComService::getMaster($v['company_id']);
					$desc = $v['code'].'-'.$service['title'];
					$result = ArchivesService::archives_check($v['id']);
					$company = Db::name('system_company')->where(['id'=>$v['company_id']])->find();
					if($result == 2){
						//扣除次数
						$re = PointService::frequencyDetAdd($master['mid'],$company['mid'],$v['contract_id'],$service['id'],2,1,$desc,$master['unique']);
						if($re){
							Db::name('system_member_count')->where(['member_id'=>$master['mid'],'service_id'=>$service['id']])->setDec('surplus');
							Db::name('system_member_count')->where(['member_id'=>$master['mid'],'service_id'=>$service['id']])->setInc('used');
						}
					}else{
						//扣除服务点
						$re = PointService::pointDetAdd($master['mid'],$company['mid'],$v['contract_id'],2,$service['point'],$desc,$master['unique']);
						if($re){
							Db::name('system_company')->where(['mid'=>$master['mid']])->setDec('point', $service['point']);
						}
					}
				}
			}
		}
	}
}
